package com.gitee.wsl.text.replacer

/**
 * 构造
 *
 * @param lookup 被查找的键值对
 */
class QuickReplacer(vararg lookup: List<Pair<String, String>>) : AbstractStrReplacer() {
    private val lookupMap: MutableMap<String, String> = mutableMapOf()
    private val prefixSet: MutableSet<Char> = mutableSetOf()
    private var minLength = 0
    private var maxLength = 0

    init {
        var minLength = Int.MAX_VALUE
        var maxLength = 0
        var key: String
        var keySize: Int
        for (pair in lookup) {
            key = pair[0].first
            lookupMap[key] = pair[1].second
            prefixSet.add(key[0])
            keySize = key.length
            if (keySize > maxLength) {
                maxLength = keySize
            }
            if (keySize < minLength) {
                minLength = keySize
            }
        }
        this.maxLength = maxLength
        this.minLength = minLength
    }

    override fun replace(str: CharSequence, pos: Int, out: Appendable): Int {
        if (prefixSet.contains(str[pos])) {
            var max = maxLength
            if (pos + maxLength > str.length) {
                max = str.length - pos
            }
            var subSeq: CharSequence
            var result: String?
            for (i in max downTo minLength) {
                subSeq = str.subSequence(pos, pos + i)
                result = lookupMap[subSeq.toString()]
                if (null != result) {
                    out.append(result)
                    return i
                }
            }
        }
        return 0
    }
}

fun StrReplacer.Companion.quick(vararg lookup: List<Pair<String, String>>) = QuickReplacer(*lookup)